import 'package:app_links/app_links.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:easy_debounce/easy_debounce.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyLogger.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:ecy_app_flutter/routes/goods/EcyGoodsPage.dart';
import 'package:ecy_app_flutter/routes/my/EcyMyPage.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../EcyRouter.dart';
import '../constant/EcyEventConsnt.dart';
import '../constant/color_constant.dart';
import '../ecycommon/EcyEnvironment.dart';
import '../ecycommon/EcyEventBus.dart';
import '../ecycommon/EcyVersion.dart';
import '../ecycommon/utils/EcyStorage.dart';
import 'consignment/EcyConsignmentMainPage.dart';
import 'group/EcyGroupMainPage.dart';

/// APP最外层容器  控制tabView的切换
class ContainPage extends StatefulWidget {
  final AppLinks appLinks;
  final int initialIndex;
  ContainPage({required Key key, required this.appLinks, this.initialIndex = 0}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return _ContainPageState();
  }
}

class _Item {
  final String name;
  final String icon;
  final String activeIcon;
  _Item({required this.name, required this.icon, required this.activeIcon});
}

class _ContainPageState extends State<ContainPage> {
  EventBus eventBus = EventBus();
  late List<Widget> pages;
  final defaultItemColor = const Color.fromARGB(255, 125, 125, 125);
  final itemNames = [
    _Item(
        name: '吃谷',
        icon: 'assets/images/ic_tab_home_normal.png',
        activeIcon: 'assets/images/ic_tab_home_active.png'),
    _Item(
        name: '谷圈',
        icon: 'assets/images/ic_tab_group_normal.png',
        activeIcon: 'assets/images/ic_tab_group_active.png'),
    _Item(
        name: '寄售',
        icon: 'assets/images/ic_tab_shiji_normal.png',
        activeIcon: 'assets/images/ic_tab_shiji_active.png'),
    _Item(
        name: '我的',
        icon: 'assets/images/ic_tab_profile_normal.png',
        activeIcon: 'assets/images/ic_tab_profile_active.png'),
  ];
  late List<BottomNavigationBarItem> itemList;
  late EcyGoodsPage goodsPage;
  late EcyConsignmentMainPage consignmentMainPage;
  late EcyGroupMainPage groupMainPage;
  late EcyMyPage myPage;
  late Map<String, String> appLinkParas;

  @override
  void initState() {
    super.initState();
    _initDeepLinks();
    _selectIndex = widget.initialIndex;
    _refreshVersion();

    goodsPage = EcyGoodsPage();
    groupMainPage = EcyGroupMainPage();
    consignmentMainPage = EcyConsignmentMainPage();
    myPage = EcyMyPage();

    pages = [goodsPage, groupMainPage, consignmentMainPage, myPage];
    itemList = itemNames
        .map((item) => BottomNavigationBarItem(
            icon: Image.asset(
              item.icon,
              width: 30,
              height: 30,
            ),
            label: item.name,
            activeIcon: Image.asset(item.activeIcon, width: 30, height: 30)))
        .toList();

    EcyEventBus().on(EcyEventConst.kLogout, (arg) {
      if (mounted) {
        setState(() {
          _selectIndex = 0;
        });
      }
    });
  }

  void finalRegister() {
    widget.appLinks.uriLinkStream.listen((Uri uri) {
      EasyDebounce.debounce(
          'my-debouncer', // <-- An ID for this particular debouncer
          Duration(milliseconds: 500), // <-- The debounce duration
          () {
        _handleDeepLink(uri);
      } // <-- The target method
          );
    });
  }

  void _initDeepLinks() async {
    final appLink = await widget.appLinks.getInitialLink();
    if (appLink != null) {
      _handleDeepLink(appLink);
    }

    finalRegister();
  }

  void _refreshVersion() async {
    var coldStartFlag = await EcyStorage.getString(EcyEventConst.kOnColdStart) == "1";
    if(coldStartFlag) {
      EcyVersion().getVersion(context);
      EcyStorage.setString(EcyEventConst.kOnColdStart, "0");
    }
  }

  String buildUrlWithParams(String baseUrl, Map<String, String> params) {
    final queryString = params.entries
        .map((e) =>
            '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}')
        .join('&');

    if (baseUrl.contains("goodsid")) {
      return '$baseUrl&$queryString';
    } else {
      return '$baseUrl?$queryString';
    }
  }

  void _handleDeepLink(Uri uri) {
    appLinkParas = uri.queryParameters;
    EcyLogger.log("_handleDeepLink" + appLinkParas.toString());
    String url = buildUrlWithParams(appLinkParas["path"] ?? "", appLinkParas);
    EcyLogger.log("_handleDeepLink2" + url);

    if (url!.isNotEmpty &&
        (url.contains(EcyEnvironment.test.domain) ||
            url.contains(EcyEnvironment.dev.domain) ||
            url.contains(EcyEnvironment.prod.domain))) {
      setTimeout(
          milliseconds: 500,
          callback: () {
            EcyRouter.push(context, url, {"h5Title": "商品详情", "h5Url": url});
          });
    }
  }

  int _selectIndex = 0;
  //Stack 层叠布局 +offset 解决状态被重置的问题
  Widget _getPagesWidget(int index) {
    return Offstage(
      offstage: _selectIndex != index,
      child: TickerMode(
        enabled: _selectIndex == index,
        child: pages[index],
      ),
    );
  }

  @override
  void didUpdateWidget(ContainPage oldWidget) {
    print('didUpdateWidget _ContainPageState');
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ColorConstant.White,
        body: Stack(
          children: <Widget>[
            _getPagesWidget(0),
            _getPagesWidget(1),
            _getPagesWidget(2),
            _getPagesWidget(3),
          ],
        ),
        bottomNavigationBar: BottomNavigationBar(
          backgroundColor: const Color(0xffffffff),
          items: itemList,
          onTap: (index) {
            setState(() {
              _selectIndex = index;
            });
            if(index == 3) {
              myPage.reloadData();
              myPage.reloadOrderData();
            }
          },
          currentIndex: _selectIndex,
          type: BottomNavigationBarType.fixed,
          selectedFontSize: 10.sp,
          unselectedFontSize: 10.sp,
          iconSize: 21.w,
          selectedItemColor: Colors.pinkAccent,
          unselectedItemColor: defaultItemColor,
          showUnselectedLabels: true,
          showSelectedLabels: true,
        ));
  }
}
